﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http.Tracing;
using NLog;

namespace TfsStatus.Infrastructure
{
	public class NLogTraceWriter : ITraceWriter
	{
		private static readonly Lazy<Dictionary<TraceLevel, Action<string>>> _loggingMap =
			new Lazy<Dictionary<TraceLevel, Action<string>>>(() => new Dictionary<TraceLevel, Action<string>>
			{ 
				{ TraceLevel.Info,  LogManager.GetCurrentClassLogger().Info },
				{ TraceLevel.Debug, LogManager.GetCurrentClassLogger().Debug },
				{ TraceLevel.Error, LogManager.GetCurrentClassLogger().Error },
				{ TraceLevel.Fatal, LogManager.GetCurrentClassLogger().Fatal },
				{ TraceLevel.Warn,  LogManager.GetCurrentClassLogger().Warn }
			});

		public bool IsEnabled(string category, TraceLevel level)
		{
			return true;
		}

		public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
		{
			if (level != TraceLevel.Off)
			{
				TraceRecord record = new TraceRecord(request, category, level);
				traceAction(record);
				Log(record);
			}
		}

		private void Log(TraceRecord record)
		{
			var message = string.Empty;

			if (record.Request != null)
			{
				if (record.Request.Method != null)
					message += " " + record.Request.Method;

				if (record.Request.RequestUri != null)
					message += " " + record.Request.RequestUri;
			}

			if (!string.IsNullOrWhiteSpace(record.Category))
				message += " " + record.Category;

			if (!string.IsNullOrWhiteSpace(record.Operator))
				message += " " + record.Operator + " " + record.Operation;

			if (!string.IsNullOrWhiteSpace(record.Message))
				message += " " + record.Message;

			if (record.Exception != null)
			{
				message += record.Exception.GetBaseException().Message;
			}

			_loggingMap.Value[record.Level](message);
		}
	}
}